package com.autoscript.ui.template.function;

import com.autoscript.ui.helper.HttpClientUtil;
import com.autoscript.ui.helper.UIPropertyHelper;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封装http get请求  格式:httpget(url)
 *                  返回json格式
 */
public class HttpGet implements TemplateMethodModel {
    private static final Logger log = LoggerFactory.getLogger(HttpGet.class);

    @Override
    public Object exec(List list) throws TemplateModelException {
        if(list.size()!=1){
            throw new TemplateModelException(UIPropertyHelper.getString("exception.func_para_number_not_match","httpGet",list.size(),1));
        }
        String url = (String) list.get(0);
        try {
            Map<String, String> headerMap= new HashMap<>();
            headerMap.put("Content-Type","application/json;charset=UTF-8");
            return HttpClientUtil.getByHeader(url,headerMap);
        } catch (IOException e) {
//            e.printStackTrace();
            log.error("httpget失败",e);
            throw new TemplateModelException("请求"+url+"失败!");
        }
    }
}
